class Solution {
public:
    int removeDuplicates(vector<int>& nums)
    {
        int count = 1;
        for (int i = 1; i < nums.size();)
        {
            if (nums[i] == nums[i - 1])
            {
                count++;
                i++;
            }
            else
            {
                if (count > 2)
                    i = nums.erase(nums.begin() + i - count + 2, nums.begin() + i) - nums.begin();
                i++;
                count = 1;
            }
        }
        if (count > 2)
            nums.erase(nums.end() - count + 2, nums.end());
        return nums.size();
    }
};